<?php
/**
 * Created by PhpStorm.
 * User: Manlin
 * Date: 2019/7/30
 * Time: 下午3:43
 */
namespace App\Storage;

use EasySwoole\Component\Pool\Exception\PoolEmpty;
use EasySwoole\Component\Pool\Exception\PoolException;
use EasySwoole\Component\Singleton;
use EasySwoole\Mysqli\Exceptions\Exception;
use EasySwoole\RedisPool\Redis;

class ChatAutoReplyCache
{
    use Singleton;
    protected $table = 'chat_auto_reply_cache';

    function __construct($shopId)
    {
        $this->table .= '_' . $shopId;
    }

    /**
     * @param $shopId
     * @return mixed
     * @throws PoolEmpty
     * @throws PoolException
     */
    function set($shopId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        if ($redis) {
            $data = ChatAutoReply::getInstance()->get(['shop_id' => $shopId]); // sql中查出来
            if (isset($data) && !empty($data)) {
                return $redis->setEx($this->table, 300, json_encode($data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); // 存300秒
            } else {
                throw new PoolException(static::class." pool exception");
            }
        } else {
            throw new PoolEmpty(static::class." pool is empty");
        }
    }

    /**
     * @param $shopId
     * @return mixed
     */
    function get($shopId) {
        try{
            $redis = Redis::getInstance()->pool('redis')::defer();

            if ($redis) {
                $data = $redis->get($this->table);
                if ($data) {
                    echo 1;
                    return json_decode($data,true);
                } else {
                    $this->set($shopId);
                    $this->get($shopId);
                }
            } else {
                throw new PoolEmpty(static::class." pool is empty");
            }
        } catch (\Exception $exception) {
            echo $exception->getMessage();
        }

    }
}